/*
 * JHeuristics - The Java Meta-Heuritics Library
 * Copyright (C) 2004-2005, Universidade Federal de Campina Grande. All rights reserved.
 * 
 * This library is free software; you can redistribute it and/or
 * modify it under the terms of the GNU Lesser General Public
 * License as published by the Free Software Foundation; either
 * version 2.1 of the License, or (at your option) any later version.
 * 
 * This library is distributed in the hope that it will be useful,
 * but WITHOUT ANY WARRANTY; without even the implied warranty of
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
 * Lesser General Public License for more details.
 * 
 * You should have received a copy of the GNU Lesser General Public
 * License along with this library; if not, write to the Free Software
 * Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA  02111-1307  USA
 */
package org.jheuristics.ga.operators.reproductors;

import org.epanetgrid.otimizacao.log.AGLogger;
import org.epanetgrid.otimizacao.util.OtimizacaoUtil;
import org.jheuristics.Individual;
import org.jheuristics.ga.GAConfig;
import org.jheuristics.ga.GAStatus;
import org.jheuristics.ga.exception.IllegalIndividualException;
import org.jheuristics.ga.operators.Probability;
import org.jheuristics.ga.operators.Reproductor;


/**
 * TODO
 *
 * @author Marcell Manfrin, marcell@ourgrid.org, Jan 9, 2006
 */
public abstract class AbstractXOver extends AbstractReproductorDecorator {

	protected AGLogger logger = AGLogger.getInstance();
	
    /**
     * TODO
     *
     * @param probability
     * @param tryOuts
     */
    public AbstractXOver(Probability probability, int tryOuts) {
        super(probability, tryOuts);
    }

    /**
     * TODO
     *
     * @param decoretedReproductor
     * @param probability
     * @param tryOuts
     */
    public AbstractXOver(Reproductor decoretedReproductor, Probability probability, int tryOuts) {
		super(decoretedReproductor, probability, tryOuts);
	}

	/**
	 * TODO
	 *
	 * @return
	 * @see org.jheuristics.ga.operators.Reproductor#getRequiredNumberOfParents()
	 */
	public int getRequiredNumberOfParents() {
		return 2;
	}


    /* (non-Javadoc)
     * @see org.jheuristics.ga.operators.Reproductor#reproduce(org.jheuristics.Individual[], org.jheuristics.ga.GAStatus, org.jheuristics.ga.GAConfig)
     */
    public Individual[] reproduce(Individual[] parents, GAStatus status, GAConfig config) {
    	if (null == parents) {
			// TODO: ERROR MSG
            throw new NullPointerException();
    	}
    	if (2 > parents.length) {
			// TODO: ERROR MSG
    		throw new IllegalArgumentException();
    	}
    	for (int i = 0; i < 2; i++) {
    		if (null == parents[i]) {
    			// TODO: ERROR MSG
                throw new NullPointerException();
    		}
    	}
        if (null == config) {
			// TODO: ERROR MSG
            throw new NullPointerException();
        }
    	Individual[] result = null;
    	StringBuffer buffer = new StringBuffer();
    	buffer.append("Verificando probabilidade de cruzamento normal:");
    	buffer.append("\n");
    	if (getProbability().check(status, config)) {
    		buffer.append("Cruzamento normal será efetuado entre: ");
    		buffer.append("\n");
    		buffer.append("Pai 1: ");
    		buffer.append(OtimizacaoUtil.format(parents[0]));
    		buffer.append("\n");
    		buffer.append("Pai 2: ");
    		buffer.append(OtimizacaoUtil.format(parents[1]));
    		buffer.append("\n");
    	    for (int i = 0; i <= getMaxBadReproductionAttempts() && null == result; i++) {
    	        try {
    	            result = xover(parents, status, config);
    	            break;
    	        } catch (IllegalIndividualException e) {
    	            // if gens aren accept try again
    	        	if(i == getMaxBadReproductionAttempts()) {
    	        		buffer.append("Número máximo de tentativas atingido.\n");
    	        	}
    	        }
    	    }
    	}else {
    		buffer.append("Cruzamento normal Não será efetuado");
    		buffer.append("\n");
    	}
    	if (null == result) {
    		result = new Individual[] {parents[0], parents[1]};
    	}
    	if (null != getDecoratedReproductor()) {
    		decorate(result, status, config);
    	}
    	logger.debug(buffer);
    	
		return result;
    }

	/**
	 * TODO
	 *
	 * @param parents
	 * @param status
	 * @param config
	 * @return
	 */
	protected abstract Individual[] xover(Individual[] parents, GAStatus status, GAConfig config);

}
